<template>
  <div class="container">
    <section class="f-mtp10">
      <div class="u-title">
        <h2>筛选查询</h2>
      </div>
      <div class="u-content u-filter f-ptp10">
        <el-input class="f-mrt20 f-mbt10 f-w250" clearable v-model="userName" placeholder="用户姓名"></el-input>
        <el-input class="f-mrt20 f-mbt10 f-w250" clearable v-model="mobileNo" placeholder="手机号码"></el-input>
        <el-date-picker
          class="f-mrt20 f-mbt10 f-w120"
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>

        <el-button class="f-h40 f-mbt10" @click="getList" type="primary">查询</el-button>
        <el-button class='f-h40' @click="exportBtnClickEvent" type="success">导出excel</el-button>
      </div>
    </section>
    <div class="f-mtp20">
      <div class="u-title">
        <h2>提现列表</h2>
        <router-link class="u-title-btn" to="/home/withdrawCashSetting">提现设置</router-link>
      </div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="withdrawOrderId" label="提现编号" width="210"></el-table-column>
        <el-table-column prop="amount" label="提现金额" width="150">
          <template slot-scope="scope">
            <span>￥{{formatPrice(scope.row.amount)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="accountType" label="用户类型" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.accountType == 'user'" class="s-c-green f-csp">用户</span>
            <span v-else-if="scope.row.accountType == 'lawyer'">律师</span>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="申请时间" width="180">
          <template slot-scope="scope">
            <span>{{format(scope.row.createTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="申请状态" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.state == 'applying'" class="s-c-green f-csp">申请中</span>
            <span v-if="scope.row.state == 'approved'" class="s-c-green f-csp">已通过</span>
            <span v-if="scope.row.state == 'rejected'" class="s-c-green f-csp">已拒绝</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobileNo" label="用户账号" width="180"></el-table-column>
        <el-table-column prop="bankAccount" label="银行卡号" width="180"></el-table-column>
        <el-table-column prop="bankName" label="所属银行" width="180"></el-table-column>
        <el-table-column prop="manage" label="操作">
          <template slot-scope="scope">
            <span
              @click="billBtnClickEvent(scope.$index, scope.row)"
              class="s-c-green f-csp f-mrt10"
            >账单</span>
            <span
              v-if="scope.row.state == 'applying'"
              @click="agree(scope.row)"
              class="s-c-green f-csp f-mrt10"
            >同意</span>
            <span
              v-if="scope.row.state == 'applying'"
              @click="disAgree(scope.row)"
              class="s-c-red f-csp"
            >拒绝</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="f-ptp20 f-pbt20">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          background
          :total="totalCount"
        ></el-pagination>
      </div>
    </div>

    <el-dialog
      title="账单信息"
      :visible.sync="showBidding"
      :before-close="handleCloseBill"
      center
      width="900px"
    >
      <div>
        <div class="f-ptp10">
          <el-table :data="billList" border style="width: 100%">
            <!-- <el-table-column prop="lawyerId" label="收入来源" width="120"></el-table-column> -->
            <el-table-column prop="paidPrice" label="金额" width="60"></el-table-column>
            <el-table-column prop="orderSn" label="订单编号" width="180"></el-table-column>
            <el-table-column prop="payType" label="支付方式" width="120">
              <template slot-scope="scope">
                <span>{{formatPayType(scope.row.payType)}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="支付状态" width="120">
              <template slot-scope="scope">
                <span>{{scope.row.state == 'unpaid' ? '未支付' : '已支付'}} {{scope.row.cityName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userId" label="来源用户id" width="120"></el-table-column>
            <el-table-column prop="caseId" label="所属案件id"></el-table-column>
            <el-table-column prop="updateTime" label="操作时间" width="150">
              <template slot-scope="scope">
                <span>{{format(scope.row.createTime)}}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="f-oh f-mtp10" v-if="billTotalCount > 0">
          <el-pagination
            class="f-fr"
            @current-change="handleBillCurrentChange"
            :current-page.sync="billCurrentPage"
            :page-size="pageSize"
            background
            layout="total, prev, pager, next"
            :total="billTotalCount"
          ></el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showBidding = false">取 消</el-button>
        <!-- <el-button type="primary" @click="showBidding = false">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "WithdrawCashManage",
  data() {
    return {
      mobileNo: null,
      userName: null,
      billUserType: null,
      billUserId: null,
      billList: [],
      billTotalCount: null,
      issueDetail: "",
      currentPage: 1,
      billCurrentPage: 1,
      pageSize: 10,
      showBidding: false,
      totalCount: 0,
      province: "",
      city: "",
      date: null,
      showDetial: false,
      tableData: [],
      caseType: ""
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 导出按钮点击事件
    exportBtnClickEvent() {
      if (this.totalCount > 0) {
        this.getAllList();
      }
    },
     // 导出所有数据
    exportAllExcel(list) {
      console.log('list::', list);
      let sheet1 = {
            "!ref": "A1:" + XLSX.utils.encode_cell({c: 7, r: list.length + 1}),
            A1: { v: "提现编号", t: "s" },
            B1: { v: "提现金额", t: "s" },
            C1: { v: "用户类型", t: "s" },
            D1: { v: "申请时间", t: "s" },
            E1: { v: "申请状态", t: "s" },
            F1: { v: "用户账号", t: "s" },
            G1: { v: "银行卡号", t: "s" },
            H1: { v: "所属银行", t: "s" },
          }
      for(let i = 0; i < list.length; i++) {
        let column_1 = XLSX.utils.encode_cell({c: 0, r: i + 1});
        let column_2 = XLSX.utils.encode_cell({c: 1, r: i + 1});
        let column_3 = XLSX.utils.encode_cell({c: 2, r: i + 1});
        let column_4 = XLSX.utils.encode_cell({c: 3, r: i + 1});
        let column_5 = XLSX.utils.encode_cell({c: 4, r: i + 1});
        let column_6 = XLSX.utils.encode_cell({c: 5, r: i + 1});
        let column_7 = XLSX.utils.encode_cell({c: 6, r: i + 1});
        let column_8 = XLSX.utils.encode_cell({c: 7, r: i + 1});
        sheet1[column_1] = {
          v: list[i].withdrawOrderId,
          t: "s"
        }
        sheet1[column_2] = {
          v: '￥' + list[i].amount,
          t: "s"
        }
        sheet1[column_3] = {
          v: list[i].accountType == 'lawyer' ? '律师' : '用户',
          t: "s"
        }
        
        sheet1[column_4] = {
          v: list[i].createTime,
          t: "d"
        }
        let state = '';
        if(list[i].state == 'approved') {
          state = '已通过';
        } else if(list[i].state == 'rejected') {
          state = '已拒绝';
        } else {
          // applying
          state = '申请中';
        }
        sheet1[column_5] = {
          v: state,
          t: "s"
        }
        sheet1[column_6] = {
          v: list[i].mobileNo,
          t: "s"
        }
        sheet1[column_7] = {
          v: list[i].bankAccount,
          t: "s"
        }
        sheet1[column_8] = {
          v: list[i].bankName,
          t: "s"
        }

      }
      console.log('sheet1:::', sheet1);
      const workbook = {
        FileName: "export.xlsx",
        SheetNames: ["Sheet1"],
        Sheets: {
          Sheet1: sheet1
        }
      };
      const workbookOut = XLSX.write(workbook, {
        bookType: "xlsx",
        bookSST: false,
        type: "array"
      });
      var date = new Date();
      var fileName = "提现_" + date.getFullYear() + '_' + (date.getMonth() + 1) + '_' + date.getDate() + ".xlsx";
      try {
        FileSaver.saveAs(
          new Blob([workbookOut], {
            type: "application/octet-stream"
          }),
          fileName
          // "user.xlsx"
        ); //trade-publish.xlsx 为导出的文件名
      } catch (e) {
        console.log(e, workbookOut);
      }
      return workbookOut;
    },


    handleCloseBill() {
      this.showBidding = false;
      this.billUserType = null;
      this.billUserId = null;
    },
    handleBillCurrentChange(page) {
      this.billCurrentPage = page;
      this.getBillList();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    },
    formatPrice(price) {
      return this._utils.formatPrice(price);
    },
    formatPayType(payType) {
      if (payType == "wechatpay") {
        return "微信支付";
      }
      if (payType == "alipay") {
        return "支付宝支付";
      }
      if (payType == "unionpay") {
        return "银联支付";
      }
    },
    getCaseType(caseType) {
      console.log("caseType:::", caseType);
    },
    format(date) {
      return this._utils.format(date, "yyyy-mm-dd");
    },
    getList() {
      const _this = this;
      const params = {
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize
      };

      if(!this._utils.isEmpty(this.userName)) {
        params.userName = this.userName;
      }
      if(!this._utils.isEmpty(this.mobileNo)) {
        params.mobileNo = this.mobileNo;
      }

      if (
        this._utils.getType(this.date) === "Array" &&
        this.date.length === 2
      ) {
        params.startDay = this._utils.format(this.date[0], "yyyy-mm-dd");
        params.endDay = this._utils.format(this.date[1], "yyyy-mm-dd");
      }

      this.$store
        .dispatch("GET_WITHDRAW_LIST", params)
        .then(res => {
          if (res.data.retCode == 0) {
            _this.tableData = res.data.data;
            _this.totalCount = res.data.totalCount;
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        })
        .catch(err => {
          console.error("获取问题列表：：", err);
        });
    },
    getAllList() {
      const params = {
        pageNum: 0,
        pageSize: this.totalCount,
      };

      if(!this._utils.isEmpty(this.userName)) {
        params.userName = this.userName;
      }
      if(!this._utils.isEmpty(this.mobileNo)) {
        params.mobileNo = this.mobileNo;
      }

      if (
        this._utils.getType(this.date) === "Array" &&
        this.date.length === 2
      ) {
        params.startDay = this._utils.format(this.date[0], "yyyy-mm-dd");
        params.endDay = this._utils.format(this.date[1], "yyyy-mm-dd");
      }

      this.$store
        .dispatch("GET_WITHDRAW_LIST", params)
        .then(res => {
          if (res.data.retCode == 0) {
            this.exportAllExcel(res.data.data);
          } else {
            this.$message.warning('获取导出数据发生错误！');
          }
        })
        .catch(err => {
          this.$message.warning('获取导出数据发生错误！');
          console.error("获取问题列表：：", err);
        });
    },
    billBtnClickEvent(index, row) {
      // 账单 按钮点击事件
      console.log("index:::", index);
      console.log("row:::", row);
      this.showBidding = true;
      this.currentCase = row;
      this.billUserType = row.accountType;
      this.billUserId = row.userId;
      this.getBillList();
      //this.getApplyList(row.caseId);
    },
    // 获取账单列表
    getBillList() {
      if (!this.billUserType) {
        return;
      }
      var params = {
        pageNum: this.billCurrentPage - 1,
        pageSize: this.pageSize
      };

      if (this.billUserType == "lawyer") {
        params.lawyerId = this.billUserId;
      } else {
        params.userId = this.billUserId;
      }
      this.$store
        .dispatch("GET_ORDER_CASE_list", params)
        .then(res => {
          console.log("res:::", res);
          if (res.data.retCode == 0) {
            this.billList = res.data.data;
            this.billTotalCount = res.data.totalCount;
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        })
        .then(err => {
          console.log("err::", err);
        });
    },
    // 审核通过
    agree(row) {
      console.log("delete", row);
      const params = {
        id: row.id,
        state: "approved"
      };
      this.$confirm(
        "确定申请单号为：" + row.withdrawOrderId + "通过审核？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$store
          .dispatch("UPDATE_WITHDRAW", params)
          .then(ress => {
            this.getList(ress);
          })
          .catch(err => {
            console.error("获取问题列表：：", err);
          });
      });
    },
    // 审核通过
    disAgree(row) {
      console.log("delete", row);
      const params = {
        id: row.id,
        state: "rejected"
      };
      this.$confirm(
        "确定拒绝申请单号为：" + row.withdrawOrderId + "审核？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$store
          .dispatch("UPDATE_WITHDRAW", params)
          .then(ress => {
            this.getList(ress);
          })
          .catch(err => {
            console.error("获取问题列表：：", err);
          });
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.top {
  /* display: flex; */
  overflow: hidden;
  padding: 10px 0;
}
.top-item {
  float: left;
  margin-right: 20px;
}
.w-120 {
  width: 120px;
}
.w-200 {
  width: 200px;
}
</style>
